package com._21cn.cms.site.web.controller;

import com._21cn.cms.common.Constants;
import com._21cn.cms.common.FormSelector;
import com._21cn.cms.site.entity.Region;
import com._21cn.cms.site.entity.Site;
import com._21cn.cms.site.service.RegionService;

import com._21cn.cms.site.service.SiteService;
import com._21cn.cms.template.entity.Template;
import com._21cn.cms.template.service.TemplateService;
import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.base.controller.BaseController;
import com._21cn.framework.utils.DateUtil;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/site/region")
public class RegionController extends BaseController{

	private static String listView = "/admin/site/region/list";
    private static String showView = "/admin/site/region/show";
    private static String jsonView = "/admin/site/region/json";
    private static String formView = "/admin/site/region/form";
    private static String redirectListView = "redirect:/admin/site/region/list.do";

    private Map<String, String> propertyTitleMap = null;

    @Autowired
    private RegionService regionService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private TemplateService templateService;
	
	@Autowired(required = false)
    @Qualifier("regionValidator")
    private Validator regionValidator;

    @RequestMapping("/list")
    public String listRegion(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", listView);
        setRequestModelMap( request, model, true );
        model.addAttribute( "statusMap", FormSelector.getStatusMap() );
        model.addAttribute( "regionTypeMap", FormSelector.getRegionTypeMap() );
        return view;
    }

    @RequestMapping("/search")
    public String searchRegion(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        Integer select = reqInfo.getIntParameter("select", 0);
        setRequestModelMap( request, model, true );

        if(select.equals(1)){  //请求类型  1 接口、0普通
            Map<String, Object> resultMap = new HashMap<String,Object>();
            String ids = reqInfo.getParameter("ids", null);
            List<Integer> idList = StringUtil.str2IntList(ids);
            if( idList.size()>0 ){
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("inIdList", idList);
                params.put("eqStatus", Constants.STATUS_ENABLE);
                List<Region> list = regionService.getList(params, Constants.DEFAULT_FIRST_PAGE_NO, Constants.DEFAULT_PAGE_SIZE_COMMON);
                for(Region region : list){
                    resultMap.put(region.getId()+"", region.getName());
                }
            }
            model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(resultMap) );
            return view;
        }else {
            PageList<Region> result = getPageList( model );
            for(Region region : result){
                Site site = siteService.getById(region.getSiteId());
                if( site!=null ){
                    region.setSiteName(site.getName());
                }
                String templateIds = region.getTemplateIdList();
                List templateIdList = StringUtil.str2IntList(templateIds);
                Map params = new HashMap();
                params.put("inIdList", templateIdList);
                List<Template> list = this.templateService.getList(params, 1, 10, false);
                String templateNames = "";
                for (Template template : list) {
                    templateNames = templateNames + template.getId() + ":" + template.getName() + "&nbsp;&nbsp;&nbsp;";
                }
                region.setTemplateName(templateNames);
            }
            model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat) );
            return view;
        }
    }

    @RequestMapping("/show")
    public String showRegion(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", showView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            Region region = regionService.getById( id );
            if( region == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
//            model.addAttribute( "statusMap", FormSelector.getStatusMap());
            model.addAttribute( "region", region );
        }
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/edit")
    public String editRegion(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", formView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Region region = new Region();
        if( id > 0 ){
            region = regionService.getById(id);
            if( region == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
        }
        model.addAttribute("region", region );
        model.addAttribute("statusMap", FormSelector.getStatusMap());
        model.addAttribute("regionTypeMap", FormSelector.getRegionTypeMap());
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/save")
    public String saveRegion(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Region region = new Region();
        if( id>0 ){                                         //更新
            region = regionService.getById( id );
            if( bind( request, region, model,  regionValidator).hasErrors() ){
                return formView;
            }
            regionService.update( region );
        }else{                                              //添加
            if( bind( request, region, model,  regionValidator).hasErrors() ){
                return formView;
            }
            regionService.insert( region );
        }
        region = regularRegion(region);
        this.regionService.update(region);
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    private Region regularRegion(Region region) {
        Integer id = region.getId();
        if (region.getType().equals(Integer.valueOf(2))) {
            if (StringUtil.isEmpty(region.getPath())) {
                int day = DateUtil.getDay(new Date());
                Site site = (Site)this.siteService.getById(region.getSiteId());
                if ((site != null) && (!StringUtil.isEmpty(site.getCode()))) {
                    String url = "/region/" + day + "/" + id + "_{templateId}.html";
                    String path = "/data/" + site.getCode() + url;
                    region.setUrl(url);
                    region.setPath(path);
                    return region;
                }
            }
        } else {
            region.setUrl("");
            region.setPath("");
        }
        return region;
    }
	
	@RequestMapping("/updateStatus")
    public String updateRegionStatus(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        if( status < 0 ){
            model.clear();
            return redirectListView+ "?" + reqInfo.getParameter( "queryParam", "" );
        }
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            regionService.update( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping("/delete")
    public String deleteRegion(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            regionService.delete( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping("/select")
    public String selectColumn(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        setRequestModelMap( request, model, true );
        PageList<Region> result = getPageList( model );
        for(Region region : result){
            Site site = siteService.getById(region.getSiteId());
            if( site!=null ){
                region.setSiteName(site.getName());
            }
        }
        model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result) );
        return view;
    }
	
	private PageList<Region> getPageList(ModelMap model) {
        if(model.containsKey("likeName"))
            model.put("likeName",model.get("likeName").toString().toLowerCase());
        PageList<Region> regionList = regionService.getList( model, Integer.parseInt(model.get("pageNo").toString()), Integer.parseInt(model.get("pageSize").toString()) );
        model.addAttribute( "regionList", regionList);
        model.addAttribute( "objList", regionList);
        model.addAttribute( "pageTurn", regionList.getPageTurn());
        model.addAttribute( "titleMap", getPropertyTitleMap() );
        return regionList;
    }

    private Map<String, String> getPropertyTitleMap() {
        if( propertyTitleMap == null ){
			propertyTitleMap = new HashMap<String,String>();
			propertyTitleMap.put( "id", "id" );
			propertyTitleMap.put( "siteId", "siteId" );
			propertyTitleMap.put( "name", "name" );
			propertyTitleMap.put( "type", "type" );
			propertyTitleMap.put( "templateId", "templateId" );
			propertyTitleMap.put( "path", "path" );
			propertyTitleMap.put( "url", "url" );
			propertyTitleMap.put( "status", "status" );
			propertyTitleMap.put( "memo", "memo" );
			propertyTitleMap.put( "createTime", "createTime" );
			propertyTitleMap.put( "createUserId", "createUserId" );
			propertyTitleMap.put( "modifyTime", "modifyTime" );
			propertyTitleMap.put( "modifyUserId", "modifyUserId" );
        }
        return propertyTitleMap;
    }
}
